#include "ruleEngine.h"

void ruleEngine::assertBSON(mongo::BSONObj b,std::string head)
{
    using namespace std;
    using namespace mongo;
    set<string> fnames;
    set<string>::iterator i;
    b.getFieldNames(fnames);
    BSONObj embedded;
    int flag;
    for(i=fnames.begin();i!=fnames.end();i++)
    {
        flag=0;
        string fieldname=(*i);
        string assertString="("+head+fieldname+" ";
        char buff[10]="\0";
        switch(b[fieldname].type())
        {
            case String:
            assertString+="\""+ b[fieldname].str()+ "\"";
            flag=1;
            break;
            case NumberDouble:
            sprintf(buff,"%f",b[fieldname].numberDouble());
            assertString+=buff;
            flag=1;
            break;
            case NumberInt:
            sprintf(buff,"%d",b[fieldname].numberInt());
            assertString+=buff;
            flag=1;
            break;
            case NumberLong:
            sprintf(buff,"%lld",b[fieldname].numberLong());
            assertString+=buff;
            flag=1;
            break;
            case jstOID:
            assertString+="\"" + b[fieldname].__oid().toString() + "\"";
            flag=1;
            break;
            case Object:
            embedded=b[fieldname].Obj();
            assertBSON(embedded,fieldname+".");
            break;
        }
        if (flag)
        {
            assertString+=")";
            char a[1024]="\0";
            strcpy(a,assertString.c_str());
            //cout<<a<<endl;
            AssertString(a);
        }
    }
}
ruleEngine::ruleEngine(std::string fname)
{
    InitializeEnvironment();
    char buff[1024]="\0";
    strcpy(buff,fname.c_str());
    Load(buff);
}
std::list<std::string> ruleEngine::match(mongo::BSONObj b)
{
    Reset();
    rmatch.clear();
    assertBSON(b,"");
    Run(-1);
    return rmatch;
}



 
/*
int main()
{
    using namespace mongo;
    using namespace std;
    BSONObjBuilder x,xe;
    x.append("DIP","192.168.4.76");
    x.append("cve","2012-04-05-xyz");
    xe.append("_id",OID("4f7bf11ae4b0b37a41428ad3"));
    x.append("result",xe.obj());
    ruleEngine r=ruleEngine("rules.clp");
    BSONObj b=x.obj();
    cout<<b.toString()<<endl;
    list<string> m=r.match(b);
    list<string>::iterator i;
    for(i=m.begin();i!=m.end();i++)
    {
        cout<<(*i)<<endl;
    }
    list<string> n=r.match(b);
    
    for(i=n.begin();i!=n.end();i++)
    {
        cout<<(*i)<<endl;
    }
    list<string> o=r.match(b);
    for(i=o.begin();i!=o.end();i++)
    {
        cout<<(*i)<<endl;
    }
    return 0;
}
*/
